import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

// 公共布局
const Layout = () => import('@/layout')

// 路由配置
const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import('@/views/home/index'),
        meta: { title: '首页', icon: 'el-icon-s-home' }
      },
      {
        path: 'vehicle/list',
        name: 'VehicleList',
        component: () => import('@/views/vehicle/list'),
        meta: { title: '车辆列表', icon: 'el-icon-s-grid' }
      },
      {
        path: 'vehicle/detail/:id',
        name: 'VehicleDetail',
        component: () => import('@/views/vehicle/detail'),
        meta: { title: '车辆详情', activeMenu: '/vehicle/list' },
        hidden: true
      },
      {
        path: 'order/list',
        name: 'OrderList',
        component: () => import('@/views/order/list'),
        meta: { title: '我的订单', icon: 'el-icon-tickets', requiresAuth: true }
      },
      {
        path: 'order/detail/:id',
        name: 'OrderDetail',
        component: () => import('@/views/order/detail'),
        meta: { title: '订单详情', activeMenu: '/order/list', requiresAuth: true },
        hidden: true
      },
      {
        path: 'order/create',
        name: 'OrderCreate',
        component: () => import('@/views/order/create'),
        meta: { title: '创建订单', activeMenu: '/vehicle/list', requiresAuth: true },
        hidden: true
      },
      {
        path: 'user/profile',
        name: 'UserProfile',
        component: () => import('@/views/user/profile'),
        meta: { title: '个人资料', icon: 'el-icon-user-solid', requiresAuth: true }
      },
      {
        path: 'user/favorite',
        name: 'UserFavorite',
        component: () => import('@/views/user/favorite'),
        meta: { title: '我的收藏', icon: 'el-icon-star-on', requiresAuth: true }
      },
      {
        path: 'service/chat',
        name: 'ServiceChat',
        component: () => import('@/views/service/chat'),
        meta: { title: '在线客服' }
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index'),
    meta: { title: '用户登录' },
    hidden: true
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/login/register'),
    meta: { title: '用户注册' },
    hidden: true
  },
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/error/404'),
    meta: { title: '404' },
    hidden: true
  },
  {
    path: '*',
    redirect: '/404',
    hidden: true
  },
  {
    path: '/user',
    component: Layout,
    redirect: '/user/profile',
    name: 'User',
    meta: { title: '个人中心', icon: 'user' },
    children: [
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/user/profile'),
        meta: { title: '个人资料', icon: 'profile' }
      },
      {
        path: 'orders',
        name: 'Orders',
        component: () => import('@/views/user/orders'),
        meta: { title: '我的订单', icon: 'order' }
      }
    ]
  },
  {
    path: '/order/detail/:orderNo',
    component: Layout,
    hidden: true,
    children: [
      {
        path: '',
        name: 'OrderDetail',
        component: () => import('@/views/order/detail'),
        meta: { title: '订单详情', icon: 'order' }
      }
    ]
  },
  {
    path: '/order/payment/:orderNo',
    component: Layout,
    hidden: true,
    children: [
      {
        path: '',
        name: 'OrderPayment',
        component: () => import('@/views/order/payment'),
        meta: { title: '订单支付', icon: 'order', requiresAuth: true }
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 白名单路径，不需要登录也可以访问
const whiteList = ['/login', '/register', '/home', '/', '/vehicle/list', '/vehicle/detail', '/404']

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 汽车租赁平台` : '汽车租赁平台'
  
  // 获取token判断是否登录
  const hasToken = store.state.user.token
  
  // 已登录状态
  if (hasToken) {
    if (to.path === '/login' || to.path === '/register') {
      // 如果已登录，访问登录页则重定向到首页
      next({ path: '/' })
    } else {
      // 判断是否已获取用户信息
      const hasUserInfo = store.state.user.name
      
      if (hasUserInfo) {
        next()
      } else {
        // 没有用户信息，则获取用户信息
        store.dispatch('user/getInfo')
          .then(() => {
            next()
          })
          .catch(() => {
            // 获取用户信息失败，需要重新登录
            store.dispatch('user/resetToken')
            next(`/login?redirect=${to.path}`)
            Vue.prototype.$message.error('登录已过期，请重新登录')
          })
      }
    }
  } else {
    // 未登录状态
    if (whiteList.some(path => to.path.startsWith(path)) || !to.meta.requiresAuth) {
      // 白名单中的路由允许未登录访问
      next()
    } else {
      // 需要登录的页面，重定向到登录页
      next(`/login?redirect=${to.path}`)
      Vue.prototype.$message.warning('请先登录')
    }
  }
})

export default router 